package edu.bw.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 将该类作为Spring配置类,目的取代Spring的配置文件(applicationContext.xml)
 */
@Configuration
public class DBConfig {
    /*将db.properties配置文件中键值对注入到对应的属性中*/
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    /**
     * //@Bean("dataSource"): 用于返回实例(对象)的方法,相当于将方法的返回值定义成一个Bean,交给Spring管理
     *          Bean的id默认值就是方法名,也可以手动指定Bean的id(通过@Bean修改)
     *          在本例子中相当于: <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">属性注入</bean>
     * @return
     */
    @Bean("dataSource")
    public DataSource initDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * //@Bean("queryRunner")相当于<bean class="org.apache.commons.dbutils.QueryRunner" id="queryRunner">构造器注入</bean>
     * @param dataSource
     * @return
     */
    @Bean("queryRunner")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //将QueryRunner指定为多例,防止将来多线程操作安全问题,便于事务管理
    public QueryRunner initQueryRunner(DataSource dataSource) { //参数名正好为上面构建的DataSource的Bean的id
        return new QueryRunner(dataSource);
    }

}
